package com.ytjj.qmyx.supplychain.api.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.fastjson.JSONObject;
import com.ytjj.qmyx.supplychain.api.annotation.oplog.annotation.OperationLog;
import com.ytjj.qmyx.supplychain.common.api.CommonResult;
import com.ytjj.qmyx.supplychain.common.model.request.*;
import com.ytjj.qmyx.supplychain.common.model.response.*;
import com.ytjj.qmyx.supplychain.common.utils.TokenUtil;
import com.ytjj.qmyx.supplychain.mapper.BankerColumnMapper;
import com.ytjj.qmyx.supplychain.mapper.entity.*;
import com.ytjj.qmyx.supplychain.service.Impl.FreightTemplateService;
import com.ytjj.qmyx.supplychain.service.ProductService;
import com.ytjj.qmyx.supplychain.service.ShopInfoService;
import com.ytjj.qmyx.supplychain.service.ShopProductReceiveRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 商品管理
 */
@RestController
@RequestMapping("/product")
@Slf4j
public class ProductController {
    @Resource
    private ProductService productService;
    @Autowired
    private ShopProductReceiveRecordService shopProductReceiveRecordService;
    @Resource
    private BankerColumnMapper bankerColumnMapper;
    @Resource
    private FreightTemplateService freightTemplateService;
    @Autowired
    private ShopInfoService shopInfoService;

    /**
     * 选品中心-根据id查询商品详情
     *
     * @param id
     * @return
     */
    @GetMapping("/findProductSelectDetail")
    public CommonResult findProductSelectDetail(@RequestParam("id") Integer id) {
        Assert.notNull(id, "productId不能为空");
        String partentId = TokenUtil.getPartentId();
        log.info("=====findProductSelectDetail===partentId========={}",partentId);
        YxShopInfo shopInfo = new YxShopInfo();
        if (!com.alibaba.excel.util.StringUtils.isEmpty(partentId)) {
            shopInfo = shopInfoService.queryShopInfoByPartnerId(partentId);
        }
        ProductSelectDetailResponse response = productService.findProductSelectDetail(id,shopInfo.getPlateform());
        return CommonResult.success(response);
    }

    /**
     * 选品中心-根据ids查询商品详情
     *
     * @param ids
     * @return
     */
    @GetMapping("/findProductSelectDetailByIds")
    public CommonResult findProductSelectDetailByIds(@RequestParam("ids") String ids) {
        Assert.notNull(ids, "productId不能为空");
        List<ProductSelectDetailResponse> response = productService.findSupplyChainProductSelectDetail(ids);
        return CommonResult.success(response);
    }

    /**
     * 获取运费模板
     *
     * @param id
     * @return
     */
    @GetMapping("/findFreightTemplateResponse")
    public FreightTemplateResponse findFreightTemplateResponse(@RequestParam("id") Integer id) {
        Assert.notNull(id, "bankerProductId不能为空");
        return productService.findFreightTemplateResponse(id);
    }

    /**
     * 获取运费模板
     *
     * @param id
     * @return
     */
    @GetMapping("/findFreightTemplateResponseById")
    public FreightTemplateResponse findFreightTemplateResponseById(@RequestParam("id") Integer id) {
        Assert.notNull(id, "freightId不能为空");
        return productService.findFreightTemplateResponseById(id);
    }

    /**
     * 根据模板Id获取模板详情
     * @return
     */
    @GetMapping("/selectYxFreightTemplate")
    public CommonResult selectFreightTemplateResponse(Integer id) {
        return CommonResult.success(freightTemplateService.selectFreightTemplateResponse(id));
    }

    /**
     * 选品中心-查询列表
     *
     * @param product
     * @return
     */
    @PostMapping(value = "/findProduceSelect")
    public CommonResult findProduceSelect(@RequestBody ProductSelectRequest product) {
        return CommonResult.success(productService.findProduceSelect(product));
    }

    /**
     * 供应链商品列表
     *
     * @param request
     * @return
     */
    @PostMapping("/all")
    public CommonResult queryAll(@RequestBody ProductRequest request) {
        return CommonResult.success(productService.queryAll(request));
    }

    /**
     * 根据id查询商品详情
     *
     * @param id
     * @return
     */
    @GetMapping("/detail")
    public CommonResult getById(@RequestParam("id") Integer id) {
        Assert.notNull(id, "id不能为空");
        ProductResponse response = productService.getById(id);
        return CommonResult.success(response);
    }

    /**
     * 添加商品评论
     */
    @PostMapping("/addProductReviews")
    public CommonResult addProductReviews(@RequestBody ProductReviewsAddRequest request) {
        productService.addProductReviews(request);
        return CommonResult.success();
    }

    /**
     * 添加商品评论
     */
    @PostMapping("/updateProductReviews")
    public CommonResult updateProductReviews(@RequestBody ProductReviewsUpdateRequest request) {
        productService.updateProductReviews(request);
        return CommonResult.success();
    }


    /**
     * 根据ids查询商品信息
     *
     * @return
     */
    @PostMapping("/getByIds")
    public List<YxProduct> getByIds(@RequestBody ProductReceiveRequest request) {
        List<YxProduct> response = productService.getByIds(request.getProductIds());
        return response;
    }

    /**
     * 销售端领取商品后 这边做登记  在查询商品时，过滤掉已领取过的商品
     *
     * @param request
     * @return
     */
    @PostMapping("/receive")
    public CommonResult receive(@RequestBody ProductReceiveRequest request) {
        boolean result = shopProductReceiveRecordService.insertByBean(request.getShopId(), request.getProductIds());
        return result ? CommonResult.success() : CommonResult.failed("领取失败");
    }

    /**
     * 销售端移除领取记录
     *
     * @param request
     * @return
     */
    @PostMapping("/remove")
    public CommonResult remove(@RequestBody ProductReceiveRequest request) {
        boolean result = shopProductReceiveRecordService.updateStatus(request.getProductIds().get(0), request.getShopId(), request.getStatus());
        return result ? CommonResult.success() : CommonResult.failed("移除失败");
    }

    /**
     * 审核供应链商品
     *
     * @param product
     * @return
     */
    @PostMapping("/syncBankerToProduct")
    public CommonResult syncBankerToProduct(@RequestBody ProductCheckRequest product) {
        if (null == product.getBrandId()){
            product.setBrandId(0);
            product.setBrand(" ");
        }
        return CommonResult.success(productService.syncBankerToProduct(product));
    }

    /**
     * 编辑商品详情信息--app渠道
     *
     * @param goodsRequest
     * @return
     */
    @PostMapping("/updateGoods")
    @OperationLog(optModule = "PRODUCT", optType = "UPDATE", desc = "供应链商品编辑")
    public CommonResult updateGoods(@Validated @RequestBody GoodsRequest goodsRequest) {
        productService.updateGoods(goodsRequest);
        return CommonResult.success();
    }

    /**
     * 所有销售端数据
     * @return
     */
    @GetMapping("/allShopInfo")
    public CommonResult allShopInfo() {
        List<ShopInfoResponse> list = shopInfoService.queryAllShopInfo();
        return CommonResult.success(list);
    }

    /**
     * 供应链栏目列表
     *
     * @return
     */
    @GetMapping("/columnList")
    public CommonResult queryColumnList() {
        Example example = new Example(YxBankerColumn.class);
        example.createCriteria().andEqualTo("status", 1);
        List<YxBankerColumn> list = bankerColumnMapper.selectByExample(example);
        return CommonResult.success(list);
    }

    @PostMapping("/productStatusUpdate")
    @OperationLog(optModule = "PRODUCT", optType = "UPDATE", desc = "更新供应链商品状态")
    public CommonResult productStatusUpdate(@RequestBody SupplyChainProductUpdateStatusRequest request) {
        return productService.productStatusUpdate(request);
    }

    @PostMapping("/productStatusDown")
    @OperationLog(optModule = "PRODUCT", optType = "UPDATE", desc = "供应链商品下架")
    public CommonResult productStatusDown(@RequestBody SupplyChainProductUpdateStatusRequest request) {
        return productService.productStatusDown(request);
    }

    /**
     * 根据供应商商品id获取售后地址id
     */
    @GetMapping("/getAddressId")
    public Integer getAddressId(@RequestParam Integer productId) {
        return productService.getAddressId(productId);
    }

    /**
     * 根据售后地址id获取售后地址信息
     */
    @GetMapping("/getAddress")
    public YxBankerStoreAddress getAddress(@RequestParam Integer addressId) {
        return productService.getAddress(addressId);
    }

    /**
     * 根据售后地址id获取售后地址信息集合
     */
    @PostMapping("/getAddress/list")
    public Map<Integer,YxBankerStoreAddress> getAddressForMap(@RequestBody Set<Integer> addressIds){
        return productService.getAddressForMap(addressIds);
    }

    /**
     * 获取供应商信息
     */
    @PostMapping("/getBankerMsg")
    public List<BankerResponse> getBankerMsg(@RequestBody BankerRequest bankerRequest) {
        return productService.getBankerMsg(bankerRequest);
    }

    /**
     * 获取供应商商品id
     */
    @PostMapping("/getBankerProductId")
    public List<BankerProductQueryVo> getBankerProductId(@RequestBody BankerProductQueryDto dto) {
        return productService.getBankerProductId(dto);
    }

    /**
     * 获取规格库存
     */
    @PostMapping("/getSpecStock")
    public List<ProductSpecStockQureyResponse> getSpecStock(@RequestBody ProductSpecStockQureyRequest request){
        return productService.getSpecStock(request);
    }

    /**
     * 根据供应链商品标签查询关联的供应链商品id
     */
    @GetMapping("/getProductIdsByProductLabelId")
    public List<Integer> getProductIdsByProductLabelId(@RequestParam Integer productLabelId){
        return productService.getProductIdsByProductLabelId(productLabelId);
    }
    /**
     * 根据供应链商品id查询关联的供应链商品标签名称
     */
    @PostMapping("/getSupplyProductLabelByProductIds")
    public List<SupplyProductLabelResponse> getSupplyProductLabelByProductIds(@RequestBody SupplyProductLabelRequest request){
        return productService.getSupplyProductLabelByProductIds(request.getProductIds());
    }

    @PostMapping("/checkSpec")
    public boolean checkSpec(@RequestBody ProductRequest request){
        return productService.checkSpec(request.getSupplyIds(),request.getSupplyProductId());
    }

    /**
     * 查询供应链商品库存
     * @param bankerProductId
     * @return
     */
    @GetMapping("/getProductStock")
    public CommonResult getProductStock(@RequestParam("bankerProductId") String bankerProductId) {
        if (StringUtils.isEmpty(bankerProductId)) {
            return CommonResult.failed("没有需要更新的数据");
        }
        return productService.getProductStock(bankerProductId);
    }

    /**
     * 查询所有运费模板的商品id
     */
    @GetMapping("/getFreightTemplateProduct")
    public List<Integer> getFreightTemplateProduct() {
        return productService.getFreightTemplateProduct();
    }


    /**
     * 供应链商品导入
     *
     * @param request
     */
    @PostMapping("/excelImport")
    public CommonResult excelImport(@RequestBody SupplyChainRequest request) {
        //保存导入数据
        ProductImportMsg importMsg = productService.saveImportMsg(request);
        //处理
        request.setImportId(importMsg.getId());
        productService.updateProductLabelAndCategoryId(request);
        log.info("================excelImport1=================");
        return CommonResult.success();
    }


    /**
     * 获取导入记录
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/getImportMsg")
    public CommonResult getImportMsg(@RequestParam(required = false, defaultValue = "1") Integer pageNum,
                               @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        return productService.getImportMsg(pageNum, pageSize);
    }

    /**
     * 获取详情导入记录
     * @param id
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/getImportInfoMsg")
    public CommonResult getImportInfoMsg(@RequestParam Integer id,
                                   @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                   @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        return productService.getImportInfoMsg(id, pageNum, pageSize);
    }
}
